package org.tis.tools.senior.module.developer.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.tis.tools.core.web.controller.BaseController;
import org.tis.tools.core.web.vo.SmartPage;
import org.tis.tools.model.common.ResultVO;
import org.tis.tools.senior.module.core.web.util.ShiroUtil;
import org.tis.tools.senior.module.developer.controller.request.*;
import org.tis.tools.senior.module.developer.entity.SBranch;
import org.tis.tools.senior.module.developer.entity.SStandardList;
import org.tis.tools.senior.module.developer.entity.SSvnAccount;
import org.tis.tools.senior.module.developer.entity.SWorkitem;
import org.tis.tools.senior.module.developer.entity.enums.BranchType;
import org.tis.tools.senior.module.developer.entity.enums.PatchType;
import org.tis.tools.senior.module.developer.entity.vo.ProjectDetail;
import org.tis.tools.senior.module.developer.entity.vo.WorkitemBranchDetail;
import org.tis.tools.senior.module.developer.exception.DeveloperException;
import org.tis.tools.senior.module.developer.service.ISWorkitemService;
import org.tmatesoft.svn.core.SVNException;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.groups.Default;
import java.io.*;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * sWorkitem的Controller类
 *
 * @author Auto Generate Tools
 * @date 2018/06/20
 */
@RestController
@RequestMapping("/sWorkitem")
@Validated
@Api(value = "工作项controller", tags = {"工作项操作接口"})
public class SWorkitemController extends BaseController<SWorkitem> {

    @Autowired
    private ISWorkitemService sWorkitemService;

    /**
     * 新增工作项
     * @param request
     * @return
     */
    //@OperateLog(type = OperateType.ADD, desc = "新增工作项")
    @ApiOperation(value = "新增工作项", notes = "body传参")
    @PostMapping
    public ResultVO add(@RequestBody
                            @Validated({WorkitemAddAndUpdateRequest.add.class, Default.class})
                            WorkitemAddAndUpdateRequest request) {

        return ResultVO.success("新增成功！",  sWorkitemService.add(request));
    }

    /**
     * 修改工作项信息
     * @param request
     * @return
     */
    //@OperateLog(type = OperateType.UPDATE, desc = "修改工作项信息")
    @ApiOperation(value = "修改工作项接口", notes = "body传参")
    @PutMapping
    public ResultVO update(@RequestBody
                               @Validated({WorkitemAddAndUpdateRequest.update.class, Default.class})
                                    WorkitemAddAndUpdateRequest request) {

        return ResultVO.success("修改成功！",  sWorkitemService.update(request));
    }

    @ApiOperation(value = "查询工作项详情", notes = "url传参")
    @GetMapping("/{guidWorkitem}")
    public ResultVO detail(@PathVariable
                           @ApiParam(name = "guidWorkitem", value = "工作项guid", required = true)
                           @NotNull(message = "id不能为空")
                                   Integer guidWorkitem) {
        SWorkitem workitem = sWorkitemService.selectById(guidWorkitem);
        if (workitem == null) {
            return ResultVO.error("404", "找不到对应记录或已经被删除！");
        }
        return ResultVO.success("查询成功", workitem);
    }

    /**
     * 查询所有工作项及分页
     *
     * @param page
     * @return
     */
    @ApiOperation(value = "查询所有工作项及分页", notes = "body传参")
    @PostMapping("/list")
    public ResultVO list(@RequestBody
                         @ApiParam(name = "page", value = "分页对象", required = true)
                         @Validated
                                 SmartPage<WorkitemBranchDetail> page) throws ParseException {

        Page<WorkitemBranchDetail> workitemDetailPage = new Page<>
                (page.getPage().getCurrent(), page.getPage().getSize(),
                        page.getPage().getOrderByField(), page.getPage().getAsc());

        return ResultVO.success("查询成功",
                sWorkitemService.workitemFullPathDetail(workitemDetailPage, getWrapper(page.getCondition())));
    }

    /**
     * 查询登录用户的工作项
     *
     * @return
     */
    @ApiOperation(value = "查询登录用户的工作项", notes = "不传参")
    @GetMapping
    public ResultVO loadLoginUserWork() {

        SSvnAccount sSvnAccount = ShiroUtil.getUser();
        List<SWorkitem> swList = sWorkitemService.selectWorkitemByUser(sSvnAccount.getUserId());

        return ResultVO.success("查询成功", swList);
    }

    /**
     * 修改工作项状态为已取消
     *
     * @return
     */
    //@OperateLog(type = OperateType.UPDATE, desc = "关闭工作项")
    @ApiOperation(value = "修改工作项状态为已取消", notes = "url传参")
    @PutMapping("/{workitemGuid}/status")
    public ResultVO updateItemStatus(@PathVariable
                                     @ApiParam(name = "workitemGuid", value = "工作项guid", required = true)
                                     @NotNull(message = "工作项id不能为空")
                                             Integer workitemGuid) {
        sWorkitemService.updateStatusCancel(workitemGuid);
        return ResultVO.success("修改成功！");
    }

    /**
     * 修改工作项状态为已投产
     *
     * @return
     */
    //@OperateLog(type = OperateType.UPDATE, desc = "工作项投产状态修改")
    @ApiOperation(value = "修改工作项状态为已投产", notes = "url传参")
    @PutMapping("/{workitemGuid}/putProductStatus")
    public ResultVO updateStatusPutProduct(@PathVariable
                                           @ApiParam(name = "workitemGuid", value = "工作项guid", required = true)
                                           @NotNull(message = "工作项id不能为空")
                                                   Integer workitemGuid) throws ParseException {

        sWorkitemService.updateStatusPutProduct(workitemGuid);
        return ResultVO.success("修改成功!");
    }


    /**
     * 关联分支
     *
     * @param workitemGuid
     * @param guidBranch
     * @return
     */
    //@OperateLog(type = OperateType.ADD, desc = "工作项关联分支")
    @ApiOperation(value = "工作项关联分支", notes = "url传参")
    @GetMapping("/{workitemGuid}/branch/{guidBranch}")
    public ResultVO relevanceBranch(@PathVariable
                                    @ApiParam(name = "workitemGuid", value = "工作项guid", required = true)
                                    @NotNull(message = "工作项guid不能为空")
                                            Integer workitemGuid,
                                    @PathVariable
                                    @ApiParam(name = "guidBranch", value = "分支guid", required = true)
                                    @NotNull(message = "分支guid不能为空")
                                            Integer guidBranch) {
        sWorkitemService.workitemRelevanceBranch(workitemGuid, guidBranch);
        return ResultVO.success("关联成功！");
    }

    /**
     * 取消关联分支
     *
     * @param workitemGuid
     * @return
     */
    //@OperateLog(type = OperateType.ADD, desc = "工作项取消关联分支")
    @ApiOperation(value = "取消关联分支", notes = "url传参")
    @GetMapping("/{workitemGuid}/cancel")
    public ResultVO cancelBranch(@PathVariable
                                 @ApiParam(name = "workitemGuid", value = "工作项guid", required = true)
                                 @NotNull(message = "工作项id不能为空")
                                         Integer workitemGuid) {
        sWorkitemService.workitemCancelBranch(workitemGuid);
        return ResultVO.success("取消分支成功！");
    }

    /**
     * 根据工作项guid查询分支信息
     *
     * @param workitemGuid
     * @return
     */
    @ApiOperation(value = "根据工作项guid查询分支信息", notes = "url传参")
    @GetMapping("/{workitemGuid}/branchDetail")
    public ResultVO selectBranchDetail(@PathVariable
                                       @ApiParam(name = "workitemGuid", value = "工作项guid", required = true)
                                       @NotNull(message = "运行环境id不能为空")
                                               Integer workitemGuid) {
        return ResultVO.success("查询成功！", sWorkitemService.selectBranchByWorkitemGuid(workitemGuid));
    }

    /**
     * 查询可关联分支
     *
     * @return
     */
    @ApiOperation(value = "查询可关联分支", notes = "不传参")
    @GetMapping("/relevanceBranch")
    public ResultVO relevanceBranch() {
        return ResultVO.success("查询成功", sWorkitemService.mayRelevanceBranch());
    }

    /**
     * 新增工作项分支
     *
     * @param guid
     * @param request
     * @return
     * @throws SVNException
     */
    //@OperateLog(type = OperateType.ADD, desc = "新增工作项分支")
    @ApiOperation(value = "新增工作项分支", notes = "url和body传参")
    @RequiresRoles("rct")
    @PostMapping("/{guid}/branch")
    public ResultVO addBranch(@PathVariable
                              @ApiParam(name = "guid", value = "工作项guid", required = true)
                              @NotNull(message = "工作项id不能为空")
                                      Integer guid,
                              @RequestBody
                              @ApiParam(name = "request", value = "新增工作项分支对象信息", required = true)
                              @Validated
                                      WorkItemAddBranchRequest request) throws SVNException {
        if (request.getBranchType().equals(BranchType.RELEASE)) {
            throw new DeveloperException("工作项不能创建RELEASE分支！");
        }
        SBranch sBranch = new SBranch();
        sBranch.setBranchFor(request.getBranchFor());
        sBranch.setBranchType(request.getBranchType());
        sBranch.setCreater(ShiroUtil.getUser().getUserId());
        sBranch.setCreateTime(new Date());
        sWorkitemService.insertBranch(guid, sBranch);
        return ResultVO.success("新增工作项分支成功！");
    }

    /**
     * 获取工作项的工程详情
     *
     * @param guid
     * @return
     */
    @ApiOperation(value = "获取工作项的工程详情", notes = "url传参")
    @GetMapping("/{guid}/project")
    public ResultVO selectProject(@PathVariable
                                  @ApiParam(name = "guid", value = "工作项guid", required = true)
                                  @NotNull(message = "工作项id不能为空")
                                          Integer guid) throws SVNException {
        ProjectDetail result = sWorkitemService.selectProjects(guid);
        return ResultVO.success("查询成功！", result);
    }

    /**
     * 拉工程
     *
     * @param guid
     * @param request
     * @return
     * @throws SVNException
     */
    //@OperateLog(type = OperateType.ADD, desc = "拉工程")
    @ApiOperation(value = "新增工作项分支", notes = "url和body传参")
    @PostMapping("/{guid}/project")
    public ResultVO addProject(@PathVariable
                               @ApiParam(name = "guid", value = "工作项guid", required = true)
                               @NotBlank(message = "工作项id不能为空")
                                       String guid,
                               @RequestBody
                               @ApiParam(name = "request", value = "工程guid集合对象", required = true)
                               @Validated WorkItemAddProjectRequest request) throws SVNException {
        sWorkitemService.insertProjects(guid, request.getProjectGuids());
        return ResultVO.success("拉取工程成功！");
    }

    /**
     * 验证标准清单是否有代码
     *
     * @param guid
     * @return
     */
    @ApiOperation(value = "验证投放按钮是否显示", notes = "url传参")
    @GetMapping("/{guid}/isOpen")
    public ResultVO selectStandardList(@PathVariable
                                       @ApiParam(name = "guid", value = "工作项guid", required = true)
                                       @NotNull(message = "工作项id不能为空")
                                               Integer guid) {

        boolean isOpen = sWorkitemService.selectStandardListByGuid(guid);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("isOpen", isOpen);

        return ResultVO.success("成功", jsonObject);
    }

    /**
     * 查询此工作项概况
     *
     * @param guid
     * @return
     */
    @ApiOperation(value = "查询此工作项概况", notes = "url传参")
    @GetMapping("/{guid}/general")
    public ResultVO selectPutProfiles(@PathVariable
                                      @ApiParam(name = "guid", value = "工作项guid", required = true)
                                      @NotNull(message = "工作项guid不能为空")
                                              Integer guid) {

        return ResultVO.success("查询成功", sWorkitemService.selectWorkitemGeneral(guid));
    }

    /**
     * 查询此工作项的标准清单明细
     *
     * @param guid
     * @return
     */
    @ApiOperation(value = "查询此工作项的标准清单明细", notes = "url传参")
    @GetMapping("/{guid}/standardListDetail")
    public ResultVO standardListDetail(@PathVariable
                                       @ApiParam(name = "guid", value = "工作项guid", required = true)
                                       @NotNull(message = "工作项guid不能为空") Integer guid) {

        return ResultVO.success("查询成功", sWorkitemService.selectStandardListDetailByGuid(guid));
    }

    /**
     * 查询此工作项的贮藏(未选择)清单明细
     *
     * @param guid
     * @return
     */
    @ApiOperation(value = "查询此工作项的贮藏(未选择)清单明细", notes = "url传参")
    @GetMapping("/{guid}/stashListDetail")
    public ResultVO stashListDetail(@PathVariable
                                    @ApiParam(name = "guid", value = "工作项guid", required = true)
                                    @NotNull(message = "工作项guid不能为空")
                                                Integer guid) {

        return ResultVO.success("查询成功", sWorkitemService.selectStashListDetailByGuid(guid));
    }

    /**
     * 模糊查询标签
     * @param request
     * @return
     */
    @ApiOperation(value = "模糊查询标签", notes = "body传参")
    @PostMapping("/lable")
    public ResultVO lable(@RequestBody @Validated DimLableRequest request){

        if(request.getLableName() == null){
            request.setLableName("");
        }
        return ResultVO.success("查询成功",sWorkitemService.selectLableAll(request.getLableName()));
    }

    /**
     * 查询所有标签
     * @return
     */
    @ApiOperation(value = "模糊查询标签", notes = "不传参")
    @GetMapping("/lableAll")
    public ResultVO lableAll(){

        return ResultVO.success("查询成功",sWorkitemService.selectLableAll(""));
    }

    /**
     * 校验artf是否存在
     * @return
     */
    @PostMapping("/verifyArtf")
    public ResultVO verifyArtf(@RequestBody @Validated VerifyArtfRequest request){

        return ResultVO.success("校验成功", sWorkitemService.verifyArtf(request));
    }

    /**
     * 查询主页展示信息
     * @return
     */
    @ApiOperation(value = "查询主页展示信息")
    @GetMapping("/homepageShow")
    public ResultVO homepageShow(){

        return ResultVO.success("查询成功", sWorkitemService.selectHomepageShow());
    }

    /**
     * 查询主页重点追踪
     * @return
     */
    @ApiOperation(value = "查询主页重点追踪")
    @PostMapping("/workProfiseDetail")
    public ResultVO workProfiseDetail(@RequestBody
                                          @ApiParam(name = "request", value = "模糊查询参数对象")
                                                  HomePageShowEmphasisRequest request){
        return ResultVO.success("查询成功",sWorkitemService.selectWorkitemProfilesDetail(request));
    }

    /**
     * 查询此工作项的所有标准清单代码
     * @param guid
     * @return
     */
    @ApiOperation(value = "查询此工作项的所有标准清单代码")
    @PostMapping("/{guid}/standardListAll")
    public ResultVO standardListAll(@PathVariable
                                    @ApiParam(name = "guid", value = "工作项guid", required = true)
                                    @NotNull(message = "工作项guid不能为空")
                                            Integer guid,
                                    @RequestBody
                                    @ApiParam(name = "page", value = "分页对象", required = true)
                                    @Validated
                                            SmartPage<SStandardList> page){
        Page<SStandardList> sStandardListPage = new Page<>
                (page.getPage().getCurrent(), page.getPage().getSize(),
                        page.getPage().getOrderByField(), page.getPage().getAsc());

        return ResultVO.success("查询成功", sWorkitemService.selectStandardListAll(
                            guid, sStandardListPage, getWrapper(page.getCondition())));
    }

    /**
     * 生成回退申请
     * @param request
     * @return
     */
    @ApiOperation(value = "生成回退申请")
    @PostMapping("/rollBack")
    public ResultVO rollBack(@RequestBody
                             @ApiParam(name = "request", value = "模糊查询参数对象")
                             RollBackAddRequest request){
        SSvnAccount user = ShiroUtil.getUser();
        sWorkitemService.createRollback(user.getUserId(), request);
        return ResultVO.success("回退申请生成成功");
    }

    /**
     * 查询工作项所有回退申请
     * @param guid
     * @return
     */
    @ApiOperation(value = "查询工作项所有回退申请")
    @GetMapping("/{guid}/rollbackByGuidWorkitem")
    public ResultVO rollbackByGuidWorkitem(@PathVariable
                                               @ApiParam(name = "guid", value = "工作项guid", required = true)
                                               @NotNull(message = "工作项guid不能为空")
                                                       Integer guid){
        return ResultVO.success("查询成功",sWorkitemService.selectRollbackByGuidWorkitem(guid));
    }

    /**
     * 查询回退申请明细
     * @return
     */
    @ApiOperation(value = "查询回退申请明细")
    @GetMapping("/rollbackListByGuid/{guid}")
    public ResultVO rollbackListByGuid(@PathVariable
                                       @ApiParam(name = "guid", value = "回退申请guid", required = true)
                                       @NotNull(message = "回退申请guid不能为空")
                                               Integer guid){
        return ResultVO.success("查询成功",sWorkitemService.selectRollbackListByGuid(guid));
    }

    /**
     * 查询此工作项的所有延迟投产申请
     * @param guid
     * @return
     */
    @ApiOperation(value = "查询此工作项的所有延迟投产申请")
    @GetMapping("/{guid}/RepealAll")
    public ResultVO RepealAll(@PathVariable
                                           @ApiParam(name = "guid", value = "工作项guid", required = true)
                                           @NotNull(message = "工作项guid不能为空")
                                                   Integer guid){
        return ResultVO.success("查询成功",sWorkitemService.selectRepealAll(guid));
    }

    /**
     * 导出一个工作项的标准清单
     *
     * @param response
     * @param guid
     * @return
     */
    //@OperateLog(type = OperateType.QUERY, desc = "导出工作项标准清单")
    @ApiOperation(value = "导出一个工作项的所有清单", notes = "url传参")
    @PostMapping("/{guid}/standardListExcel")
    public ResultVO standardListExcel(HttpServletResponse response,
                                      @PathVariable
                                      @ApiParam(name = "guid", value = "工作项guid", required = true)
                                      @NotNull(message = "工作项guid不能为空")
                                              Integer guid) {

        SSvnAccount user = ShiroUtil.getUser();
        if (user == null) {
            throw new DeveloperException("尚未登录，请登录后再操作！");
        }
        SWorkitem workitem = sWorkitemService.selectById(guid);
        List<SStandardList> standardLists = sWorkitemService.exportStandardList(guid);

        OutputStream os = null;
        InputStream is = null;
        try {
            is = this.getClass().getResourceAsStream("/template/excel.xls");
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
            HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
            createSheet(standardLists, hssfSheet, user);
            String fileName = workitem.getItemName() + "_" + workitem.getOwner();
            response.setCharacterEncoding("utf-8");
            response.setHeader("content-disposition", "attachment;filename=" + new String(
                    fileName.getBytes(), "ISO8859-1") + ".xls");
            os = response.getOutputStream();
            hssfWorkbook.write(os);
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
            throw new DeveloperException("导出清单异常！");
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ResultVO.success("导出成功");
    }

    /**
     * 导出多个工作项的标准清单
     *
     * @param response
     * @param guids
     * @return
     */
    //@OperateLog(type = OperateType.QUERY, desc = "导出工作项标准清单")
    @ApiOperation(value = "导出多个工作项的所有清单", notes = "body传参")
    @PostMapping("/standardListExcels")
    public ResultVO standardListExcels(HttpServletResponse response,
                                      @RequestBody
                                      @ApiParam(name = "guids", value = "工作项guid", required = true)
                                      @NotEmpty(message = "工作项guid集合不能为空")
                                              List<Integer> guids) throws IOException {

        SSvnAccount user = ShiroUtil.getUser();
        if (user == null) {
            throw new DeveloperException("尚未登录，请登录后再操作！");
        }
        // 用于存放生成的excel文件名称
        List<String> fileNames = new ArrayList<>();
        String filePath = this.getClass().getResource("/").getPath() + "/template/execl/";
//        this.getClass().get
        // 得到此路径下文件
        File fileDir = new File(filePath);
        //创建文件夹
        if (!fileDir.exists() && !fileDir.isDirectory()) {
            fileDir.mkdirs();
        }
        // 导出Excel文件路径
        String fullFilePath = "";
        //输出流
        OutputStream os = null;
        //输入流
        InputStream in = null;
        for (Integer guid:guids){
            List<SStandardList> standardLists = sWorkitemService.exportStandardList(guid);
            SWorkitem workitem = sWorkitemService.selectById(guid);
            String fileName = workitem.getItemName() + "_" + workitem.getOwner() + ".xls";
            in = this.getClass().getResourceAsStream("/template/excel.xls");
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook(in);
            HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
            createSheet(standardLists, hssfSheet, user);
            // 导出excel的全路径
            fullFilePath = filePath + File.separator + fileName;
            fileNames.add(fullFilePath);
            os = new FileOutputStream(fullFilePath);
            // 写文件
            hssfWorkbook.write(os);
            //清空流缓冲区数据
            os.flush();
            //关闭流
            os.close();
            in.close();
            os = null;
        }

        //导出压缩文件的全路径
        String zipFilePath = filePath + "清单"+".zip";
        //导出zip
        File zip = new File(zipFilePath);
        //将excel文件生成压缩文件
        File srcfile[] = new File[fileNames.size()];
        for (int j = 0, n1 = fileNames.size(); j < n1; j++) {
            srcfile[j] = new File(fileNames.get(j));
        }
        ZipFiles(srcfile, zip);
        response.setCharacterEncoding("utf-8");
        response.setHeader("content-disposition", "attachment;filename=" + new String(
                zip.getName().getBytes(), "ISO8859-1") + ".xls");
        OutputStream outputStream = response.getOutputStream();
        InputStream inputStream = new FileInputStream(zipFilePath);
        byte[] buffer = new byte[1024];
        int i = -1;
        while ((i = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, i);
        }
        outputStream.flush();
        outputStream.close();
        inputStream.close();

        try {
            // 删除完里面所有内容
            delAllFile(filePath);
            java.io.File myFilePath = new java.io.File(filePath);
            myFilePath.delete(); // 删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultVO.success("导出成功");
    }

    /**
     * 组装execl表格
     * @param standardLists
     * @param hssfSheet
     * @param user
     */
    public void createSheet(List<SStandardList> standardLists, HSSFSheet hssfSheet, SSvnAccount user){
        for (int i = 0; i < standardLists.size(); i++) {
            SStandardList sdl = standardLists.get(i);
            HSSFRow row = hssfSheet.createRow(i + 2);
            row.createCell(0).setCellValue("/" + sdl.getPartOfProject());
            row.createCell(1).setCellValue(sdl.getPatchType());
            row.createCell(2).setCellValue("*." + sdl.getPatchType());
            row.createCell(3).setCellValue(sdl.getDeployWhere());
            if (PatchType.ECD.equals(sdl.getPatchType())) {
                row.createCell(4).setCellValue("/" + sdl.getFullPath());
            } else {
                row.createCell(4).setCellValue("/" + sdl.getFullPath().substring(
                        sdl.getFullPath().indexOf(sdl.getPartOfProject())));
            }
            row.createCell(5).setCellValue("all");
            row.createCell(6).setCellValue("all");
            row.createCell(7).setCellValue(user.getUserId());
        }
    }

    //压缩文件
    public void ZipFiles(File[] srcfile, File zipfile) {
        byte[] buf = new byte[1024];
        try {
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
                    zipfile));
            for (int i = 0; i < srcfile.length; i++) {
                FileInputStream in = new FileInputStream(srcfile[i]);
                out.putNextEntry(new ZipEntry(srcfile[i].getName()));
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            }
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /***
     * 删除指定文件夹下所有文件
     *
     * @param path 文件夹完整绝对路径
     * @return
     */
    public static  boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
                flag = true;
            }
        }
        return flag;
    }
}

